﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;
using TemplateLibraryConnector.Data;
using TemplateLibraryConnector.Utility;
using TemplateLibraryConnector.UI;

namespace TemplateLibraryConnector
{
    public class TemplateLibraryConnectorConfig : ListPageBase
    {
        protected Label TestLabel;
        protected TextBox TextError;
        protected TreeView TreeSourceDocLib;
        private TemplateLibraryConnectorSettings _settings;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (Page.IsPostBack) return;
            HideError();

            string siteUrl = List.ParentWeb.Url;
            

            TemplateLibraryConnectorSettings settings;
            try
            {
                settings = TemplateLibraryConnectorSettings.LoadFromList(List) ??
                           TemplateLibraryConnectorSettings.Default;
            }
            catch (Exception ex)
            {
                // Suppress settings: Load from defaults
                settings = TemplateLibraryConnectorSettings.Default;
                ShowError("Error loading list settings - Loaded default values instead.<br/><br/>Details: {0}", ex.Message);
            }
            if (settings != null)
                _settings = settings;

            


            var selectedTemplateLibraries = TemplateLibraryConnectorUtility.GetSelectedTemplateLibraries(_settings);
            PopulateTree(TreeSourceDocLib, selectedTemplateLibraries, siteUrl);

            // Load the description field
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            Uri libSettingsUrl = null;
            if (Request.UrlReferrer != null)
                Uri.TryCreate(Request.UrlReferrer.AbsoluteUri, UriKind.Absolute, out libSettingsUrl);

            
            _settings = new TemplateLibraryConnectorSettings();

            if (TreeSourceDocLib.CheckedNodes.Count > 0)
            {
                for (int i = 0; i < TreeSourceDocLib.CheckedNodes.Count; i++)
                {
                    TreeNode node = TreeSourceDocLib.CheckedNodes[i];
                    string[] webAndList = node.Value.Split('|');
                    if (webAndList.Length == 2)
                    {
                        _settings.WebIds = string.IsNullOrEmpty(_settings.WebIds) ? webAndList[0] : _settings.WebIds + "," + webAndList[0];
                        _settings.TemplateListIds = string.IsNullOrEmpty(_settings.TemplateListIds) ? webAndList[1] : _settings.TemplateListIds + "," + webAndList[1];
                    }
                    else 
                    {
                        // Idstring is corrupt, so show an error and bail
                        ShowError("Please select a valid Document Library in the tree view.");
                        return;
                    }
                }
            }
            else
            {
                _settings.WebIds = string.Empty;
                _settings.TemplateListIds = string.Empty;
            }

            TemplateLibraryConnectorSettings.SaveToList(List, _settings);

            if (libSettingsUrl == null) return;
            string librarySettingsUrl = GetLibrarySettingsUrl(libSettingsUrl);

            if (Request.QueryString["Referer"] != null && Request.QueryString["DestinationList"] != null)
            {
                SPUtility.Redirect(string.Format("{0}?IsDlg=1&DestinationList={1}", Request.QueryString["Referer"], Request.QueryString["DestinationList"]), SPRedirectFlags.Default, HttpContext.Current);
            }
            else
            {
                SPUtility.Redirect(librarySettingsUrl, SPRedirectFlags.Default, HttpContext.Current);
            }
        }

        public static string GetLibrarySettingsUrl(Uri libSettingsUrl)
        {
            string path = GetSiteSegment(libSettingsUrl.Segments);

            return string.Format("{0}://{1}{2}{3}{4}",
                                 libSettingsUrl.Scheme,
                                 libSettingsUrl.DnsSafeHost,
                                 path,
                                 "_layouts/listedit.aspx",
                                 libSettingsUrl.Query);
        }

        public static string GetSiteSegment(string[] segments)
        {
            int layoutSegment = 0;
            for (int i = segments.Length; i > 0; i--)
                if (segments[i-1] == "_layouts/")
                    layoutSegment = i-2;

            string retVal = string.Empty;
            for (int i = 0; i <= layoutSegment; i++)
                retVal += segments[i];

            return retVal;
        }

        private void PopulateTree(TreeView treeView, IEnumerable<string> nodes, string defaultHubAddress)
        {
            var siteUrl = _settings.GetTemplateHubAddress(defaultHubAddress);
            using (var site = new SPSite(siteUrl))
            {
                string relativeSubWebUrl = siteUrl.Replace(site.Url, "");

                using (SPWeb web = site.OpenWeb(relativeSubWebUrl))
                {
                    var webNode = new TreeNode(web.Title, "", "/_layouts/images/folder.gif") { Expanded = true, SelectAction = TreeNodeSelectAction.None, ShowCheckBox = false };
                    treeView.Nodes.Add(webNode);

                    TemplateLibraryConnectorUtility.AddRelevantDocumentLibraries(web, webNode, nodes);
                }
            }
        }

        
        private void HideError()
        {
            TextError.Visible = false;
        }

        private void ShowError(string format, params string[] args)
        {
            TextError.Text = string.Format(format, args);
            TextError.Visible = true;
        }

        }

    }
